$(document).ready(function () {
//返回一个添加了contextPath的url
    $.url = function (url) {
        return url;
    };
    $.fn.order = {};
//进出口
    $.fn.order.type = $("input[name='declaration_type']").val();
//是否为出口，默认为出口
    $.fn.order.isExport = $.fn.order.type !== "I";
//贸易类型
    $.fn.order.tradeType = $("input[name='tradeType']").val();
//是否为一般贸易
    $.fn.order.isGeneralTrade = $.fn.order.tradeType == "0";
//是否为加工贸易
    $.fn.order.isProcessTrade = $.fn.order.tradeType == "1";
//是否为特殊贸易
    $.fn.order.isSpecialTrade = $.fn.order.tradeType == "2";
//通关类别
    $.fn.order.isTongguanYth = $("input[name='isTongguanYth']").val();

    $.fn.api.settings.api = {
        "supCompany": "/order-dropdown/supCompany?isExport=" + $.fn.order.isExport + "&isCCI="
                      + (isTongguanYth === "1"),
        "supCompanyOffer": '/business/declarationOffer-getDeclarationOfferFree',
        "company": "/order-dropdown/company?key={query}",
        "goodsCode": "/order-dropdown/goods-code?key={query}",
        "cciExportPort": '/order-dropdown/tgyihSupCompany?isTongguanYth=1&code={query}',
        "searchPort": '/api/dictionary/search?dtGroupCode=FingerPort',
        "cusList" : '/order-dropdown/custComList?key={query}'
    };
});
var dropdownConfig = [
        {
            "key": "supCompany.id",
            "data": [{"code": "1", "id": "", "name": "请先选择申报口岸"}],
            // "api": {action: "supCompany", all: true},
            afterSelected: function (row, value, text, $choice, $selected) {
                if (value.length == 0) {
                    return;
                }
                var com_customs_code = "";
                var __supCom = {};
                for (var i = 0; i < $.data.supComData.length; i++) {
                    var supCom = $.data.supComData[i];
                    if (supCom.value == value) {
                        com_customs_code = supCom.data.com_customs_code;
                        __supCom = supCom;
                    }
                }
                var shenbaoDropdown = $("input[name='shenbao_company_co']").parent();
                shenbaoDropdown.dropdown("set value", com_customs_code);
                shenbaoDropdown.dropdown("set text", com_customs_code);
                $("input[name='shenbao_company_name']").val(text);
                // var exprotPortDp = $("input[name='export_port_code']").parent();
                // exprotPortDp.dropdown("set value", row.data.port_code);
                // exprotPortDp.dropdown("set text", row.data.port);
                // $("input[name='export_port']").val(row.data.port);
                // var shenbaoPortDp = $("input[name='declaration_port_code']").parent();
                // shenbaoPortDp.dropdown("set value", row.data.port_code);
                // shenbaoPortDp.dropdown("set text", row.data.port);
                //--------------------------------------------------
                //------显示报关费用，免柜数，特殊说明
                //--------------------------------------------------
                InitFunctions.getSupCompanyOffer(value);

                /*if ($(".ui.allform").find(".error").length) {
                 $(".ui.allform").form("is valid");
                 }*/
                //----------------------------------------------------------------
                //----申报单位联动
                //----------------------------------------------------------------
                $("input[name='shenbao_company_co']").val(__supCom.data.com_customs_code);
                $("input[name='shenbao_company_co_unite']").val(__supCom.data.companyCoUnite);
                $("input[name='shenbao_company_name']").val(__supCom.name);
            }
        },//报关行
        {
            "key": "export_port_code", "data": DROPDOWN_DATA.export_port,
            afterSelected: function (row, value, text, $choice, $selected) {
                if (value.length == 0) {
                    return;
                } else {
                    requestSupCompniesInfo._init();
                }
                addRemark(detailsPack);
            }
        },//出口口岸
        {
            "key": "declaration_port_code",
            "api": {
                action: "supCompany"
            },
            onRemoteQuerySuccess: function (response, element) {
                console.log(response);
                var module_id = $(element).dropdown("get").id();
                var module = $.fn.dropdown.find(module_id);
                var model_fields = module.get.setting().fields;
                var results = response[model_fields.remoteValues];
                var export_ports = DROPDOWN_DATA.export_port;
                var filteredPorts = [];
                var query = module.get.query();
                var queryReg = new RegExp(query);
                var filterMap = {};
                for (var i = 0; i < export_ports.length; i++) {
                    var export_port = export_ports[i];
                    var showText = "(" + export_port.code + ") " + export_port.name;
                    if (query != null || query != undefined || query.trim().length != 0) {
                        if (!queryReg.test(showText)) {
                            continue;
                        }
                    }
                    $.each(results, function (j, m) {
                        if (m.data.port_code === export_port.code && filterMap[export_port.code]
                                                                     == undefined) {
                            filteredPorts.push(
                                {
                                    name: showText,
                                    value: export_port.code,
                                    text: export_port.name
                                });
                            filterMap[export_port.code] = 1;
                            return 0;
                        }
                    });
                }
                module.setup.menu({values: filteredPorts});
            },
            afterSelected: function (row, value, text, $choice) {
                if (value.length == 0) {
                    return;
                } else {
                    requestSupCompniesInfo._init();
                }
                var _$supCompanyId = $("input[name='supCompany.id']");
                if ($.data.lastPortCode && $.data.lastPortCode != value) {
                    _$supCompanyId.parent().dropdown("set").text("");
                    _$supCompanyId.val("");
                }
                $.data.lastPortCode = value;
                $.ajaxPlugin({
                                 url: $.fn.api.settings.api.supCompany,
                                 method: 'post',
                                 data: {code: value},
                                 dataType: 'json',
                                 success: function (data) {
                                     var parentDiv = _$supCompanyId.parent();
                                     var filteredSupCompany = [];
                                     var model_fields = parentDiv.dropdown('get').setting().fields;
                                     var results = data[model_fields.remoteValues];
                                     $.data.supComData = results;
                                     $.each(results, function (i, n) {
                                         filteredSupCompany.push(
                                             {
                                                 name: n.name,
                                                 value: n.value,
                                                 text: n.name
                                             });
                                         var hasSO = n.data["hasSO"];
                                         if (hasSO && hasSO == "0") {
                                             $("#SO_DIV").show();
                                         } else {
                                             $("#SO_DIV").hide();
                                         }
                                     });
                                     //排序，将佛港提前
                                     filteredSupCompany.sort(function (c1, c2) {
                                         if (c1.name.indexOf("佛港报关") > 0) {
                                             return -1;
                                         }
                                         if (c2.name.indexOf("佛港报关") > 0) {
                                             return 1;
                                         }
                                         return 0;
                                     });
                                     parentDiv.dropdown('setup').menu({values: filteredSupCompany});
                                 }
                             });
                addRemark(detailsPack);

                //----------------------------------------------------------------
                //----判断是不是申报口岸是否是佛山新港， 假如是佛山新港则显示<button>获取柜号</button>
                //----------------------------------------------------------------
                if ("5189" === value) {
                    $("#fetchBtn").show();
                } else {
                    $("#fetchBtn").hide();
                }
                //----------------------------------------------------------------
            }
        },//申报地海关
        {
            "key": "direct_transit_code",
            "data": [{"code": "ZH", "name": "直航"},
                     {"code": "ZG", "name": "转关"}],
            afterSelected: function (row, value, text, $choice) {
                if (value.length == 0) {
                    return;
                } else {
                    $("#data_type").val(text);
                    requestSupCompniesInfo._init();
                }

            }
        },//直航转关类型

        {
            "key": "company_co",//收发货人

            "api": {
                action: "company"
            },
            onRemoteQuerySuccess: function (response, element) {
                console.log(response);
                var module_id = $(element).dropdown("get").id();
                var module = $.fn.dropdown.find(module_id);
                var model_fields = module.get.setting().fields;
                var results = response[model_fields.remoteValues];
                var obj = {
                    name: '<br />请选择以下选项',
                    text: '请选择以下选项',
                    value: '请选择'
                };
                results.unshift(obj);
                var filteredPorts = [];
                var query = module.get.query();
                if (query) {
                    var queryReg = new RegExp(query);
                    $.each(results, function (i, n) {
                        var showText = n.name;
                        if (queryReg.test(showText)) {
                            filteredPorts.push({
                                                   data:n.data,
                                                   name: n.name,
                                                   value: n.value,
                                                   text: n.text
                                               });
                        }
                    });
                    module.setup.menu({values: filteredPorts});
                } else {
                    module.setup.menu({values: results});
                }

            },
            afterSelected: function (row, value, text, $choice) {
                this.dropdown("set").text(value);
                $("input[name='company_name']").val(text);
                var fahuoDropdown = $("input[name='fahuo_company_co']").parent();
                fahuoDropdown.dropdown("set value", value);
                fahuoDropdown.dropdown("set text", value);
                $("input[name='fahuo_company_name']").val(text);
                /* if ($(".ui.allform").find(".error").length) {
                 $(".ui.allform").form("is valid");
                 }*/
                if (row.data) {
                    $("input[name='company_co_unite']").val(row.data.company_co_unite);
                    $("input[name='fahuo_company_co_unite']").val(row.data.company_co_unite);
                }
                /**
                 * 填充卖方信息
                 */
                $("input[name='seller']").val(row.text);
                $.ajaxPlugin({
                                 url: "/business/companyQp/query_address_phone_fax",
                                 data: {code: value},
                                 method: 'post',
                                 dataType: 'json',
                                 success: function (apfText) {
                                     var apf = $.parseJSON(apfText);
                                     $("input[name='seller_address']").val(apf.address);
                                     $("input[name='seller_phone']").val(apf.phone);
                                     $("input[name='seller_fax']").val(apf.fax);
                                 }
                             });

                if ($.fn.order.isExport && $.fn.order.isGeneralTrade) {
                    /**
                     * 设置特殊征免性质
                     * 经营单位代码第六位，2-602（中外合作）；3-601（中外合资）；4-603（外资企业）
                     * 对应关系：征免性质
                     */

                    var judgeChar = value.charAt(5);
                    if (judgeChar == '2') {
                        $("input[name='levymode_code']").parent().dropdown("set selected", "602");
                    } else if (judgeChar == '3') {
                        $("input[name='levymode_code']").parent().dropdown("set selected", "601");
                    } else if (judgeChar == '4') {
                        $("input[name='levymode_code']").parent().dropdown("set selected", "603");
                    }
                    if ($("input[name='company_co']").parent().hasClass("error")) {
                        var validateArr = ["company_co"];
                        relateValidate("allform", validateArr);
                    }
                }
            },
            // onShow: function () {
            //     // var gets = $(this).dropdown("get");
            //     // if (gets.value()) {
            //     //     $(this).dropdown("filterItems", gets.value());
            //     // }
            //     // console.log("1");
            // },
            message: {
                noResults: "<div class='ui grid one column centered'><div class='row'>暂无输入公司，点击按钮进行添加</div><button id='addCompanyCoBtn' class='mini ui button blue' style='padding-top: 5px;padding-bottom: 6px;font-family: \"微软雅黑\", serif !important;border-radius: 0;'>添加单位</button><div class='row'></div></div>"
            }
        },
        {
            "key": "agent_for_com_id",//代录人客户公司下拉列表

            "api": {
                action: "cusList"
            },
            onRemoteQuerySuccess: function (response, element) {
                console.log(response);
                var module_id = $(element).dropdown("get").id();
                var module = $.fn.dropdown.find(module_id);
                var model_fields = module.get.setting().fields;
                var results = response[model_fields.remoteValues];
                var obj = {
                    name: '请选择',
                    text: '',
                    value: '请选择'
                };
                results.unshift(obj);
                var filteredPorts = [];
                var query = module.get.query();
                if (query) {
                    var queryReg = new RegExp(query);
                    $.each(results, function (i, n) {
                        var showText = n.name;
                        if (queryReg.test(showText)) {
                            filteredPorts.push({
                                                   data:n.data,
                                                   name: n.name,
                                                   value: n.value,
                                                   text: n.text
                                               });
                        }
                    });
                    module.setup.menu({values: filteredPorts});
                } else {
                    module.setup.menu({values: results});
                }

            },
            /*  afterSelected: function (row, value, text, $choice) {
             this.dropdown("set").text(value);
             if (row.data) {
             $("input[name='agent_for_com_id']").val(row.data.agent_for_com_id);
             $("input[name='agent_name']").val(row.data.agent_name);
             }
             },*/
            // onShow: function () {
            //     // var gets = $(this).dropdown("get");
            //     // if (gets.value()) {
            //     //     $(this).dropdown("filterItems", gets.value());
            //     // }
            //     // console.log("1");
            // },
        },
        {
            "key": "fahuo_company_co",//消费使用单位/生产单位
            "api": {action: "company"},
            afterSelected: function (row, value, text, $choice) {
                this.dropdown("set").text(value);
                $("input[name='fahuo_company_name']").val(text);
                $("input[name='fahuo_company_co_unite']").val(row.data.fahuo_company_co_unite);
            },
            message: {
                noResults: "<div class='ui grid one column centered'><div class='row'>暂无输入公司，点击按钮进行添加</div><button id='addCompanyCoBtn' class='mini ui button blue' style='padding-top: 5px;padding-bottom: 6px;font-family: \"微软雅黑\", serif !important;border-radius: 0;'>添加单位</button><div class='row'></div></div>"
            }
        },
        {
            "key": "shenbao_company_co", "api": {action: "company"},//申报单位
            afterSelected: function (row, value, text, $choice) {
                this.dropdown("set").text(value);
                $("input[name='shenbao_company_name']").val(text);
            }
        },
        {"key": "tex_company", "api": {action: "company"}},//纳税单位
        {"key": "transport_mode", "data": DROPDOWN_DATA.transportType},//运输方式
        {"key": "trade_mode", "data": DROPDOWN_DATA.tradeMode},//监管方式
        {"key": "levymode_code", "data": DROPDOWN_DATA.levyMode},//征免性质
        {
            "key": "arrived_country_code",
            "data": DROPDOWN_DATA.country,
            afterSelected: function (row, value, text, $choice) {
                if ($.fn.order.isExport) {
                    $("input[name='arrived_port_code']").parent().dropdown("set selected", value);
                    $("input[name='trading_country_code']").parent().dropdown("set selected",
                                                                              value);
                    $("#destination_code").parent().dropdown("set selected", value);
                    if ($("input[name='arrived_country_code']").parent().hasClass("error")) {
                        var validateArr = ["arrived_country_code", "arrived_port_code"];
                        relateValidate("allform", validateArr);
                    }
                }
            }
        },//运抵国
        {
            "key": "trading_country_code", "data": DROPDOWN_DATA.country,
            afterSelected: function (row, value, text, $choice) {
                //$("input[name='arrived_port_code']").parent().dropdown("set selected", value);
            }
        },//贸易国
        /*{"key": "arrived_port_code", "data": DROPDOWN_DATA.country},*///指运港
        {
            "key": "arrived_port_code",
            "api": {action: 'searchPort'},
            "isScrolLoad": true,
            "scrollLoadUrl": '/api/dictionary/search?dtGroupCode=FingerPort',
            onRemoteQuerySuccess: function (response, element) {
                var module_id = $(element).dropdown("get").id();
                var module = $.fn.dropdown.find(module_id);
                var model_fields = module.get.setting().fields;
                var results = response[model_fields.remoteValues];
                var filteredPorts = [];
                var query = module.get.query();
                var queryReg = new RegExp(query);
                var filterMap = {};
                for (var i = 0; i < results.length; i++) {
                    var showText = results[i].name;
                    if (query != null || query != undefined || query.trim().length != 0) {
                        if (!queryReg.test(showText)) {
                            continue;
                        } else if (queryReg.test(showText)
                                   && filterMap[results[i].value]
                                      == undefined) {
                            filteredPorts.push(
                                {
                                    name: showText,
                                    value: results[i].value,
                                    text: results[i].text
                                });
                            filterMap[results[i].value] = 1;
                        }
                    }
                }
                module.setup.menu({values: filteredPorts});
            }
        },
// {"key":"arrived_port_code","data":DROPDOWN_DATA.export_port},
        {
            "key": "goods_addr_code", "data": DROPDOWN_DATA.destination
        }
        ,//境内目的地
        {
            "key": "goods_package", "data": DROPDOWN_DATA.packageType,
            onHide: function () {
                var $icons = $(this).find("i");
                $.each($icons, function (i, n) {
                    if (i == 0) {
                        $(n).show();
                    } else {
                        $(n).remove();
                    }
                });
                var packIndex;
                var packSure = function () {
                    detailsPack = $(".details-packType").val();
                    addRemark(detailsPack);
                    layer.close(packIndex);
                    $("input[name='goods_package_code']").declarationJump({action: 'next'});

                };
                if ($("input[name='goods_package_code']").val() == "7") {
                    packIndex =
                    layer.alert(
                        "<div class='ui input'> <input type = 'text' placeholder = '请输入具体包装种类' class='details-packType'></div > ",
                        packSure
                    )
                    ;
                    $(".details-packType").bind("keyup", function (event) {
                        if (event.keyCode == 13) {
                            packSure();
                        }
                    });
                    $(".details-packType").focus();
                } else {
                    detailsPack = " ";
                    addRemark(detailsPack);
                }
                var $icons = $("input[name='goods_package_code']").parent().find("i");
                $.each($icons, function (i, n) {
                    if (i == 0) {
                        $(n).show();
                    } else {
                        $(n).remove();
                    }
                });
            }
        }
        ,//包装种类
        {
            "key": "freight1",
            "data": DROPDOWN_DATA.feeType,
            afterSelected: function (row, value, text, $choice) {
                if (value == "1") {
                    setNameFieldsDisabled({freight3: true}, true);
                    setInputsRequired(
                        {
                            freight1: {
                                required: true,
                                members: {
                                    freight1_code: true,
                                    freight2: true,
                                    freight3_code: false,
                                    freight3: false
                                },
                                ref_form_id: ".ui.allform",
                                ref_rule: "declarationFormRule"
                            }
                        });
                } else {
                    setNameFieldsDisabled({freight3: false}, true);
                }
            }
        }
        ,//运费计算类型
        {
            "key": "freight3", "data": DROPDOWN_DATA.currency
        }
        ,//运费币制
        {
            "key": "premium1",
            "data": DROPDOWN_DATA.feeType,
            afterSelected: function (row, value, text, $choice) {
                if (value == "1") {
                    setNameFieldsDisabled({premium3: true}, true);
                    setInputsRequired(
                        {
                            premium1: {
                                required: true,
                                members: {
                                    premium1_code: true,
                                    premium2: true,
                                    premium3_code: false,
                                    premium3: false
                                },
                                ref_form_id: ".ui.allform",
                                ref_rule: "declarationFormRule"
                            }
                        });
                } else {
                    setNameFieldsDisabled({premium3: false}, true);
                }
            }
        }
        ,//保费计算类型
        {
            "key": "premium3", "data": DROPDOWN_DATA.currency
        }
        ,//保费币制
        {
            "key": "otherfee1",
            "data": DROPDOWN_DATA.feeType,
            afterSelected: function (row, value, text, $choice) {
                if (value == "1") {
                    setNameFieldsDisabled({otherfee3: true}, true);
                    setInputsRequired(
                        {
                            otherfee1: {
                                required: false,
                                members: {
                                    otherfee1_code: true,
                                    otherfee2: true,
                                    otherfee3_code: false,
                                    otherfee3: false
                                },
                                ref_form_id: ".ui.allform",
                                ref_rule: "declarationFormRule"
                            }
                        });
                } else {
                    setNameFieldsDisabled({otherfee3: false}, true);
                }
            }
        }
        ,//杂费计算类型
        {
            "key": "otherfee3", "data": DROPDOWN_DATA.currency
        }
        ,//杂费币制
        {
            "key": "customs_type", "data": DROPDOWN_DATA.declarationType
        }
        ,//报关单类型
        {
            "key": "deal_mode",
            "data": DROPDOWN_DATA.dealMode
            ,
            afterSelected: function (row, value, text, $choice) {
                layout();//新版页面加这个函数
                switch (value) {
                    case "1":
                        //CIF
                        if ($.fn.order.isExport) {
                            setNameFieldsDisabled(
                                {
                                    goods_addr: false,
                                    freight1: false,
                                    freight2: false,
                                    freight3:  $("input[name='freight1_code']").val() == '1',
                                    premium1: false,
                                    premium2: false,
                                    premium3:  $("input[name='premium1_code']").val() == '1',
                                    otherfee1: false,
                                    otherfee2: false,
                                    otherfee3: $("input[name='otherfee1_code']").val() == '1'
                                }, true);
                            setInputsRequired(
                                {
                                    goods_addr: {
                                        required: true,
                                        members: {goods_addr_code: true},
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    freight1: {
                                        required: true,
                                        members: {
                                            freight1_code: true,
                                            freight2: true,
                                            freight3_code: $("input[name='freight1_code']").valueNotEqual('1'),
                                            freight3: $("input[name='freight1_code']").valueNotEqual('1')
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    premium1: {
                                        required: true,
                                        members: {
                                            premium1_code: true,
                                            premium2: true,
                                            premium3_code: $("input[name='premium1_code']").valueNotEqual('1'),
                                            premium3: $("input[name='premium1_code']").valueNotEqual('1')
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    otherfee1: {
                                        required: false,
                                        members: {
                                            otherfee1_code: false,
                                            otherfee2: false,
                                            otherfee3_code: $("input[name='otherfee1_code']").valueNotEqual('1'),
                                            otherfee3: $("input[name='otherfee1_code']").valueNotEqual('1')
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    }
                                });
                        } else {
                            setNameFieldsDisabled(
                                {
                                    goods_addr: false,
                                    freight1: true,
                                    freight2: true,
                                    freight3: true,
                                    premium1: true,
                                    premium2: true,
                                    premium3: true,
                                    otherfee1: false,
                                    otherfee2: false,
                                    otherfee3: false
                                }, true);
                            setInputsRequired(
                                {
                                    goods_addr: {
                                        required: true,
                                        members: {goods_addr_code: true},
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    freight1: {
                                        required: false,
                                        members: {
                                            freight1_code: false,
                                            freight2: false,
                                            freight3_code: false,
                                            freight3: false
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    premium1: {
                                        required: false,
                                        members: {
                                            premium1_code: false,
                                            premium2: false,
                                            premium3_code: false,
                                            premium3: false
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    otherfee1: {
                                        required: false,
                                        members: {
                                            otherfee1_code: false,
                                            otherfee2: false,
                                            otherfee3_code: false,
                                            otherfee3: false
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    }
                                });
                        }
                        break;
                    case "2":
                        //C&F
                        if ($.fn.order.isExport) {
                            setNameFieldsDisabled(
                                {
                                    goods_addr: false,
                                    freight1: false,
                                    freight2: false,
                                    freight3:  $("input[name='freight1_code']").val() == '1',
                                    premium1: true,
                                    premium2: true,
                                    premium3: true,
                                    otherfee1: false,
                                    otherfee2: false,
                                    otherfee3: $("input[name='otherfee1_code']").val() == '1'
                                }, true);
                            setInputsRequired(
                                {
                                    goods_addr: {
                                        required: true,
                                        members: {goods_addr_code: true},
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    freight1: {
                                        required: true,
                                        members: {
                                            freight1_code: true,
                                            freight2: true,
                                            freight3_code: $("input[name='freight1_code']").valueNotEqual('1'),
                                            freight3: $("input[name='freight1_code']").valueNotEqual('1')
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    premium1: {
                                        required: false,
                                        members: {
                                            premium1_code: false,
                                            premium2: false,
                                            premium3_code: false,
                                            premium3: false
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    otherfee1: {
                                        required: false,
                                        members: {
                                            otherfee1_code: false,
                                            otherfee2: false,
                                            otherfee3_code: $("input[name='otherfee1_code']").valueNotEqual("1"),
                                            otherfee3: $("input[name='otherfee1_code']").valueNotEqual("1")
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    }
                                });
                        } else {
                            setNameFieldsDisabled(
                                {
                                    goods_addr: false,
                                    freight1: true,
                                    freight2: true,
                                    freight3: true,
                                    premium1: false,
                                    premium2: false,
                                    premium3:  $("input[name='premium1_code']").val() == '1',
                                    otherfee1: false,
                                    otherfee2: false,
                                    otherfee3: $("input[name='otherfee1_code']").val() == '1'
                                }, true);
                            setInputsRequired(
                                {
                                    goods_addr: {
                                        required: true,
                                        members: {goods_addr_code: true},
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    freight1: {
                                        required: false,
                                        members: {
                                            freight1_code: false,
                                            freight2: false,
                                            freight3_code: false,
                                            freight3: false
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    premium1: {
                                        required: true,
                                        members: {
                                            premium1_code: true,
                                            premium2: true,
                                            premium3_code: $("input[name='premium1_code']").valueNotEqual('1'),
                                            premium3: $("input[name='premium1_code']").valueNotEqual('1')
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    otherfee1: {
                                        required: false,
                                        members: {
                                            otherfee1_code: false,
                                            otherfee2: false,
                                            otherfee3_code: $("input[name='otherfee1_code']").valueNotEqual('1'),
                                            otherfee3: $("input[name='otherfee1_code']").valueNotEqual('1')
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    }
                                });
                        }
                        break;
                    case "3":
                        //FOB
                        if ($.fn.order.isExport) {
                            setNameFieldsDisabled(
                                {
                                    goods_addr: false,
                                    freight1: true,
                                    freight2: true,
                                    freight3: true,
                                    premium1: true,
                                    premium2: true,
                                    premium3: true,
                                    otherfee1: false,
                                    otherfee2: false,
                                    otherfee3: false
                                }, true);

                            setInputsRequired(
                                {
                                    goods_addr: {
                                        required: true,
                                        members: {goods_addr_code: true},
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    freight1: {
                                        required: false,
                                        members: {
                                            freight1_code: false,
                                            freight2: false,
                                            freight3_code: false,
                                            freight3: false
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    premium1: {
                                        required: false,
                                        members: {
                                            premium1_code: false,
                                            premium2: false,
                                            premium3_code: false,
                                            premium3: false
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    otherfee1: {
                                        required: false,
                                        members: {
                                            otherfee1_code: false,
                                            otherfee2: false,
                                            otherfee3_code: false,
                                            otherfee3: false
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    }
                                }
                            );
                        } else {
                            setNameFieldsDisabled(
                                {
                                    goods_addr: false,
                                    freight1: false,
                                    freight2: false,
                                    freight3:  $("input[name='freight1_code']").val() == '1',
                                    premium1: false,
                                    premium2: false,
                                    premium3:  $("input[name='premium1_code']").val() == '1',
                                    otherfee1: false,
                                    otherfee2: false,
                                    otherfee3: $("input[name='otherfee1_code']").val() == '1'
                                }, true);
                            setInputsRequired(
                                {
                                    goods_addr: {
                                        required: true,
                                        members: {goods_addr_code: true},
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    freight1: {
                                        required: true,
                                        members: {
                                            freight1_code: true,
                                            freight2: true,
                                            freight3_code: $("input[name='freight1_code']").valueNotEqual('1'),
                                            freight3: $("input[name='freight1_code']").valueNotEqual('1')
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    premium1: {
                                        required: true,
                                        members: {
                                            premium1_code: true,
                                            premium2: true,
                                            premium3_code: $("input[name='premium1_code']").valueNotEqual('1'),
                                            premium3: $("input[name='premium1_code']").valueNotEqual('1')
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    otherfee1: {
                                        required: false,
                                        members: {
                                            otherfee1_code: false,
                                            otherfee2: false,
                                            otherfee3_code: $("input[name='otherfee1_code']").valueNotEqual('1'),
                                            otherfee3: $("input[name='otherfee1_code']").valueNotEqual('1')
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    }
                                });
                        }
                        break;
                    case "4":
                        //C&I
                        if ($.fn.order.isExport) {
                            setNameFieldsDisabled(
                                {
                                    goods_addr: true,
                                    freight1: true,
                                    freight2: true,
                                    freight3: true,
                                    premium1: false,
                                    premium2: false,
                                    premium3:  $("input[name='premium1_code']").val() == '1',
                                    otherfee1: false,
                                    otherfee2: false,
                                    otherfee3: $("input[name='otherfee1_code']").val() == '1'
                                }, true);
                            setInputsRequired(
                                {
                                    goods_addr: {
                                        required: true,
                                        members: {goods_addr_code: true},
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    freight1: {
                                        required: false,
                                        members: {
                                            freight1_code: false,
                                            freight2: false,
                                            freight3_code: false,
                                            freight3: false
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    premium1: {
                                        required: true,
                                        members: {
                                            premium1_code: true,
                                            premium2: true,
                                            premium3_code: $("input[name='premium1_code']").valueNotEqual('1'),
                                            premium3: $("input[name='premium1_code']").valueNotEqual('1')
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    otherfee1: {
                                        required: false,
                                        members: {
                                            otherfee1_code: false,
                                            otherfee2: false,
                                            otherfee3_code: $("input[name='otherfee1_code']").valueNotEqual('1'),
                                            otherfee3: $("input[name='otherfee1_code']").valueNotEqual('1')
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    }
                                });
                        } else {
                            setNameFieldsDisabled(
                                {
                                    goods_addr: false,
                                    freight1: false,
                                    freight2: false,
                                    freight3:  $("input[name='freight1_code']").val() == '1',
                                    premium1: true,
                                    premium2: true,
                                    premium3: true,
                                    otherfee1: false,
                                    otherfee2: false,
                                    otherfee3: $("input[name='otherfee1_code']").val() == '1'
                                }, true);
                            setInputsRequired(
                                {
                                    goods_addr: {
                                        required: true,
                                        members: {goods_addr_code: true},
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    freight1: {
                                        required: true,
                                        members: {
                                            freight1_code: true,
                                            freight2: true,
                                            freight3_code: $("input[name='freight1_code']").valueNotEqual('1'),
                                            freight3: $("input[name='freight1_code']").valueNotEqual('1')
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    premium1: {
                                        required: false,
                                        members: {
                                            premium1_code: false,
                                            premium2: false,
                                            premium3_code: false,
                                            premium3: false
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    otherfee1: {
                                        required: false,
                                        members: {
                                            otherfee1_code: false,
                                            otherfee2: false,
                                            otherfee3_code: $("input[name='otherfee1_code']").valueNotEqual('1'),
                                            otherfee3: $("input[name='otherfee1_code']").valueNotEqual('1')
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    }
                                });
                        }
                        break;
                    case "5":
                        //市场价
                        if ($.fn.order.isExport) {
                            setNameFieldsDisabled(
                                {
                                    goods_addr: true,
                                    freight1: false,
                                    freight2: false,
                                    freight3:  $("input[name='freight1_code']").val() == '1',
                                    premium1: false,
                                    premium2: false,
                                    premium3:  $("input[name='premium1_code']").val() == '1',
                                    otherfee1: false,
                                    otherfee2: false,
                                    otherfee3: $("input[name='otherfee1_code']").val() == '1'
                                }, true);
                            setInputsRequired(
                                {
                                    goods_addr: {
                                        required: true,
                                        members: {goods_addr_code: true},
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    freight1: {
                                        required: true,
                                        members: {
                                            freight1_code: true,
                                            freight2: true,
                                            freight3_code: $("input[name='freight1_code']").valueNotEqual('1'),
                                            freight3: $("input[name='freight1_code']").valueNotEqual('1')
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    premium1: {
                                        required: true,
                                        members: {
                                            premium1_code: true,
                                            premium2: true,
                                            premium3_code: $("input[name='premium1_code']").valueNotEqual('1'),
                                            premium3: $("input[name='premium1_code']").valueNotEqual('1')
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    otherfee1: {
                                        required: false,
                                        members: {
                                            otherfee1_code: false,
                                            otherfee2: false,
                                            otherfee3_code: $("input[name='otherfee1_code']").valueNotEqual('1'),
                                            otherfee3: $("input[name='otherfee1_code']").valueNotEqual('1')
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    }
                                });
                        } else {
                            setNameFieldsDisabled(
                                {
                                    goods_addr: false,
                                    freight1: false,
                                    freight2: false,
                                    freight3:  $("input[name='freight1_code']").val() == '1',
                                    premium1: false,
                                    premium2: false,
                                    premium3:  $("input[name='premium1_code']").val() == '1',
                                    otherfee1: false,
                                    otherfee2: false,
                                    otherfee3: $("input[name='otherfee1_code']").val() == '1'
                                }, true);
                            setInputsRequired(
                                {
                                    goods_addr: {
                                        required: true,
                                        members: {goods_addr_code: true},
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    freight1: {
                                        required: true,
                                        members: {
                                            freight1_code: true,
                                            freight2: true,
                                            freight3_code: $("input[name='freight1_code']").valueNotEqual('1'),
                                            freight3: $("input[name='freight1_code']").valueNotEqual('1')
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    premium1: {
                                        required: true,
                                        members: {
                                            premium1_code: true,
                                            premium2: true,
                                            premium3_code: $("input[name='premium1_code']").valueNotEqual('1'),
                                            premium3: $("input[name='premium1_code']").valueNotEqual('1')
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    otherfee1: {
                                        required: false,
                                        members: {
                                            otherfee1_code: false,
                                            otherfee2: false,
                                            otherfee3_code: $("input[name='otherfee1_code']").valueNotEqual('1'),
                                            otherfee3: $("input[name='otherfee1_code']").valueNotEqual('1')
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    }
                                });
                        }
                        break;
                    case "6":
                        //垫仓
                        if ($.fn.order.isExport) {
                            setNameFieldsDisabled(
                                {
                                    goods_addr: true,
                                    freight1: false,
                                    freight2: false,
                                    freight3:  $("input[name='freight1_code']").val() == '1',
                                    premium1: false,
                                    premium2: false,
                                    premium3:  $("input[name='premium1_code']").val() == '1',
                                    otherfee1: false,
                                    otherfee2: false,
                                    otherfee3: $("input[name='otherfee1_code']").val() == '1'
                                }, true);
                            setInputsRequired(
                                {
                                    goods_addr: {
                                        required: true,
                                        members: {goods_addr_code: true},
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    freight1: {
                                        required: true,
                                        members: {
                                            freight1_code: true,
                                            freight2: true,
                                            freight3_code: $("input[name='freight1_code']").valueNotEqual('1'),
                                            freight3: $("input[name='freight1_code']").valueNotEqual('1')
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    premium1: {
                                        required: true,
                                        members: {
                                            premium1_code: true,
                                            premium2: true,
                                            premium3_code: $("input[name='premium1_code']").valueNotEqual('1'),
                                            premium3: $("input[name='premium1_code']").valueNotEqual('1')
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    otherfee1: {
                                        required: false,
                                        members: {
                                            otherfee1_code: false,
                                            otherfee2: false,
                                            otherfee3_code: $("input[name='otherfee1_code']").valueNotEqual('1'),
                                            otherfee3: $("input[name='otherfee1_code']").valueNotEqual('1')
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    }
                                });
                        } else {
                            setNameFieldsDisabled(
                                {
                                    goods_addr: false,
                                    freight1: false,
                                    freight2: false,
                                    freight3:  $("input[name='freight1_code']").val() == '1',
                                    premium1: false,
                                    premium2: false,
                                    premium3:  $("input[name='premium1_code']").val() == '1',
                                    otherfee1: false,
                                    otherfee2: false,
                                    otherfee3: $("input[name='otherfee1_code']").val() == '1'
                                }, true);
                            setInputsRequired(
                                {
                                    goods_addr: {
                                        required: true,
                                        members: {goods_addr_code: true},
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    freight1: {
                                        required: true,
                                        members: {
                                            freight1_code: true,
                                            freight2: true,
                                            freight3_code: $("input[name='freight1_code']").valueNotEqual('1'),
                                            freight3: $("input[name='freight1_code']").valueNotEqual('1')
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    premium1: {
                                        required: true,
                                        members: {
                                            premium1_code: true,
                                            premium2: true,
                                            premium3_code: $("input[name='premium1_code']").valueNotEqual('1'),
                                            premium3: $("input[name='premium1_code']").valueNotEqual('1')
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    },
                                    otherfee1: {
                                        required: false,
                                        members: {
                                            otherfee1_code: false,
                                            otherfee2: false,
                                            otherfee3_code: $("input[name='otherfee1_code']").valueNotEqual('1'),
                                            otherfee3: $("input[name='otherfee1_code']").valueNotEqual('1')
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    }
                                });
                        }
                        break;
                    default:
                }
            }
        }
        ,//成交方式
//商品
        {
            "key": "#code_t",
            "api": {
                action: "goodsCode"
            }
            ,
            afterSelected: function (row, value, text, $choice) {
                this.dropdown("set text", value + row.data.code_s);
            }
            ,
            onHide: function () {
                var $icons = $(this).find("i");
                $.each($icons, function (i, n) {
                    if (i == 0) {
                        $(n).show();
                    } else {
                        $(n).remove();
                    }
                });
                var unitcodeData = $('#code_t').parent().dropdown('get selectedItem').attr(
                    'other-data');
                if (unitcodeData == undefined) {
                    return;
                }
                var selectedData = $.parseJSON($.decodeUnicode(unitcodeData));
                var $codeSInput = $("input#code_s");
                $codeSInput.val(selectedData.code_s);
                if (selectedData) {
                    var unit1 = selectedData.unit1;
                    if (unit1 && unit1 != 0) {
                        var $legalUnitDom = $("#legalUnitCode").parent();
                        $legalUnitDom.dropdown("set selected", unit1);
                        if (!$.fn.order.isExport) {
                            $legalUnitDom.addDisabledClass();
                        }
                        var $unitDom = $("#unitCode").parent();
                        /*如计价单位已有值，则不修改计价单位*/
                        if ($unitDom[0].innerText == '') {
                            $unitDom.dropdown("set selected", unit1);
                        }
                    }
                    var unit2 = selectedData.unit2;
                    var $secondUnitDom = $("#secondUnitCode").parent();
                    var $secondCount = $("#second_count").parent();
                    $("#secondUnitCode").val("");
                    $("#second_unit").val("");
                    $("#second_count").val("");
                    $secondUnitDom.find(".text").text("");
                    $secondUnitDom.addDisabledClass();
                    $secondCount.addDisabledClass();
                    addOrRemoveSecondRequired(unit2 && unit2 != 0);
                    if (unit2 && unit2 != 0) {
                        $secondUnitDom.dropdown("set selected", unit2);
                    }
                    if (!$.fn.order.isProcessTrade) {
                        if (selectedData.good_mode && $("#code_t").val()) {
                            loadLabel(selectedData.good_mode,
                                      $(this).parent().find("#goods_mode").val());
                        }
                    }
                    else {
                        if ($("#code_t").parent().hasClass("error")) {
                            var validteField = ["#code_t", "#legalUnitCode"];
                            relateValidate("commodities", validteField);
                        }
                    }
                }
                /*validateCode.call(this);*/
                /*if ($("#commodities").find(".error").length) {
                 $('.ui.goodsForm').form('is valid');
                 }*/

            }
        }
        ,//商品编号
        {
            "key": "#unit", "data": DROPDOWN_DATA.unit
        }
        ,//计价单位
        {
            "key": "#legal_unit", "data": DROPDOWN_DATA.unit
        }
        ,//第一计量单位
        {
            "key": "#second_unit", "data": DROPDOWN_DATA.unit
        }
        ,//第二计量单位
        {
            "key": "#currency", "data": DROPDOWN_DATA.currency
        }
        ,//币制
        {
            "key": "#origin_country_code", "data": DROPDOWN_DATA.country
        }
        ,//原产国
        {
            "key": "#destination_code", "data": DROPDOWN_DATA.country
        }
        ,//目的国
        {
            "key": "#levymode", "data": DROPDOWN_DATA.levy
        }
        ,//征免
//集装箱
        {
            "key": "#containerStandard", "data": DROPDOWN_DATA.containerType
        }
        ,//集装箱型号
        {
            "key": "#suifudan_co", "data": DROPDOWN_DATA.docType
        }
        ,//随附单证代码
//
        {
            "key": "special_relationship_confirm", "data": DROPDOWN_DATA.confirmState
        }
        ,//特殊关系确认
        {
            "key": "price_impact_confirm", "data": DROPDOWN_DATA.confirmState
        }
        ,//价格影响确认
        {
            "key": "payment_royaltils_confirm", "data": DROPDOWN_DATA.confirmState
        }
        ,//支付特许权使用费确认
    ]
    ;
$(document).ready(function () {
    //通关一体化时，出口口岸根据提供线下服务的供应商所对应口岸进行筛选
    if ("1" === $("#isTongguanYth").val()) {
        for (var i = 0; i < dropdownConfig.length; i++) {
            var __config = dropdownConfig[i];
            if ("export_port_code" === __config.key) {
                dropdownConfig[i] = {
                    "key": "export_port_code", "api": {action: "cciExportPort"},
                    onRemoteQuerySuccess: function (response, element) {
                        var module_id = $(element).dropdown("get").id();
                        var module = $.fn.dropdown.find(module_id);
                        var model_fields = module.get.setting().fields;
                        var results = response[model_fields.remoteValues];
                        var filteredPorts = [];
                        var query = module.get.query();
                        var queryReg = new RegExp(query);
                        var filterMap = {};
                        for (var i = 0; i < results.length; i++) {
                            var showText = "(" + results[i].data.port_code + ") "
                                           + results[i].data.port;
                            if (query != null || query != undefined || query.trim().length != 0) {
                                if (!queryReg.test(showText)) {
                                    continue;
                                } else if (queryReg.test(showText)
                                           && filterMap[results[i].data.port_code]
                                              == undefined) {
                                    filteredPorts.push(
                                        {
                                            name: showText,
                                            value: results[i].data.port_code,
                                            text: results[i].data.port
                                        });
                                    filterMap[results[i].data.port_code] = 1;
                                }
                            }
                        }
                        module.setup.menu({values: filteredPorts});
                    }
                };
            }

        }
    }
    $(".ui.dropdown").s_dropdown(dropdownConfig);
    var specialNameInit = ["company_co", "shenbao_company_co", "fahuo_company_co"];
    $.each(specialNameInit, function (i, n) {
        var $i = $("input[name='" + n + "']");
        if ($i.length != 0 && $i.val()) {
            $i.nextAll("div.text").text($i.val());
        }
    });
    //获取焦点全选文字
    $("input").focus(function () {
        $(this).select();
    });
    //添加单位按钮绑定事件
    $("body").on('click', "#addCompanyCoBtn", function () {
        var dp = $(this).parents(".dropdown:first");
        layer.open({
                       type: 2,
                       title: '添加单位',
                       area: ["500px", "350px"],
                       offset: 't',
                       content: $.url("/business/companyQp/frame_to_add_companyQP"),
                       success: function (layero, index) {
                           var f = layero.find("iframe")[0];
                           var contentHeight = f.contentDocument.body.scrollHeight;
                           var position = layero.position();
                           var __top = position.top;
                           var __left = position.left - 100;
                           if ((contentHeight + __top) > 500) {
                               __top = window.document.body.scrollTop;
                           }
                           layero.offset(
                               {
                                   top: __top, left: __left
                               });
                           $(f).height(contentHeight * 0.8);
                           dp.find("input.search").val("");
                           dp.dropdown("hide");
                       }
                   });
        return false;
    });
    showDropdownDataWhenReadPageInitialized();
    invalidInputTabActionOnDisabledDiv();

});
//要素录入框中实现统计录入字符串的长度，超过指定长度不让录入，必填项验证
var calculateBytesFunc={
    bytesLengthArr:[],//存放每个input框字符串的长度
    limitLen:255,//限制允许最大的输入长度
    filterArr:[],
    bytesCount:0,
    canCalcate:true,
    _init:function(target,str){
        var _this=this;
        this.bytesCount=0;//所有input框字符串的长度总和
        this.filterArr=[];
        this.$lengthTips=$(".lengthTips");
        this.$readOnlySpecModel=$(".readOnlySpecModel");
        this.$readOnlySpecModelHidden=$(".readOnlySpecModelHidden");
        this.val=this.$readOnlySpecModelHidden.val();
        if(this.val.length==0){
            this.arr=[];
        }else{
            this.arr=this.val.split("|");
        }
        var attrName=target.attr('name');
        var reg=/^spec\-model\-input/;
        this.currentIndex=attrName.replace(reg,'');
        this.bytesLengthArr[this.currentIndex]=this._totalBytes(str);
        this._sumBytesLengthArr();
        this.$lengthTips.find("span").text(this.bytesCount);
        this._warnOverLimitLen();
        if(this.bytesCount>this.limitLen&&!target.hasClass('ui-autocomplete-input')){
            var remainStr='';
            var surplus=this.limitLen-(this.bytesCount-this.bytesLengthArr[this.currentIndex]);
            var remainReg=/[\u4e00-\u9fa5]/;
            if(surplus>0){
                for(var i=0;i<target.val().length;i++){
                    if(remainReg.test(target.val()[i])){
                        surplus-=2;
                        remainStr+=target.val()[i];
                    }else{
                        surplus-=1;
                        remainStr+=target.val()[i];
                    }
                    if(surplus==0){
                        break;
                    }
                }
                target.val(remainStr);
                this.bytesLengthArr[this.currentIndex]=this._totalBytes(remainStr);
                _this.bytesCount=0;
                this._sumBytesLengthArr();
                this.$lengthTips.find("span").text(this.bytesCount);
                this._warnOverLimitLen();
            }else{
                target.val("");
            }
        }else{
            this._contactGoodsMode(target,str);
        }

    },
    _sumBytesLengthArr:function(){
        var _this=this;
        this.bytesLengthArr.forEach(function(item){
            _this.bytesCount+=parseInt(item);
        });
    },
    _warnOverLimitLen:function(){
        var text=parseInt(this.$lengthTips.find("span").text());
        if(text>this.limitLen){
            this.$lengthTips.find("span").addClass("warnTips");
        }else{
            if(this.$lengthTips.find("span").hasClass("warnTips")){
                this.$lengthTips.find("span").removeClass("warnTips");
            }
        }
    },
    _contactGoodsMode:function(target,str){
        var _this=this;
        this.arr[this.currentIndex]=str;
        this.arr.filter(function(item){
            if(item.trim().length){
                _this.filterArr.push(item);
            }
        });
        this.$readOnlySpecModel.val(this.filterArr.join('|'));
        this.$readOnlySpecModel.attr("title",this.filterArr.join('|'));
        this.$readOnlySpecModelHidden.val(this.arr.join('|'));
    },
    _totalBytes:function(str){
        var count=0;
        var reg=/[\u4e00-\u9fa5]/;
        for(var i=0;i<str.length;i++){
            if(reg.test(str[i])){
                count+=2;
            }else{
                count+=1;
            }
        }
        return count;
    }
};
/*选中商品编号弹出要素录入框*/
function loadLabel(arg, dataStr) {
    var requiredCount=0;//统计填了多少项必填项了
    $(".modelContainer").remove();
    var data = dataStr ? dataStr.split("|") : [];
    var childNode = '';
    var modelContainer = '<div class="modelContainer"></div>';
    var bgHtml = '<div id="bg"></div>';
    var modalHtml = '<div id="modalShow"></div>';
    var modelHtml = '<div class="ui form rightForm"><form class="loadLabelForm">';
    var sureBtn = '<button class="ui blue button right floated mini" onclick="sureFunc();" type="button">确定 </button>';
    var cancleBtn = '<button class="ui button right floated mini" onclick="cancleFunc();" type="button">取消 </button>';
    var tempArr = arg.split(";");
    var inputHtml;
    var len = tempArr.length - 1;
    var autocompleteArr = [
        [ "0 无品牌",
          "1 境内自主品牌",
          "2 境内收购品牌",
          "3 境外品牌(贴牌生产)",
          "4 境外品牌(其它)"],
        [ "0 出口货物在最终目的国(地区)不享受优惠关税",
          "1 出口货物在最终目的国(地区)享受优惠关税",
          "2 不能确定在最终目的国(地区)享受优惠关税",
          "3 不适用于进口报关单"]];
    for (var i = 0; i < len; i++) {
        var temp = data[i];
        if(i === 0 || i === 1){
            temp = autocompleteArr[i][temp];
        }
        var tempI = tempArr[i];
        if (temp) {
            while (temp.indexOf("\"") >= 0) {
                temp = temp.replace("\"", "&quot;");
            }
        }
        inputHtml =
        '<input type="text" autocomplete="off" class="spec-model-input" jumpIndex="999' + i
        + '" value="'
        + (temp ? temp : '')
        + '" name="spec-model-input' + i + '"';
        if(tempI.trim() === ":出口享惠情况"){
            inputHtml += 'id="disCountInputDp"';
        }
        if(tempI.trim() === ":品牌类型"){
            inputHtml += 'id="brandInputDp"';
        }
        inputHtml += '> ';
        var childClass = "field inline inlineGroup";
        if (tempI.trim() != ":其他" && tempI.trim() != ":GTIN" && tempI.trim() != ":CAS") {
            childClass += " " + "required";
            /*sureBtn =
             '<button class="ui blue button right floated small" onclick="sureFunc(1,' + "'" + arg
             + "'"
             + ');" type="button">确定 </button>';*/
            sureBtn =
            '<button class="ui blue button right floated mini" _id="modelSureBtn" onclick="sureFunc(1);" type="button">确定 </button>';
        }
        childNode += "<div class='" + childClass + "'><label>"
                     + tempArr[i].substring(tempArr[i].indexOf(":") + 1)
                     + "</label>" + inputHtml + "</div>";
    }
    childNode+="<div class='" + childClass + "'><label>规格型号</label><input readonly='readonly' type='text' autocomplete='off' class='spec-model-input readOnlySpecModel'name='spec-model-input"+len+"'jumpIndex='999" + len+"'><input type='hidden' class='readOnlySpecModelHidden'></div>";
    childNode+="<div><label></label><p class='lengthTips'>当前字节/总共字节:<span>0</span>/255字节</p></div>";
    childNode+="<div><label></label><p class='needRequired'>*内容为必填项</p></div>";
    /*childNode += "<div class='field'><label>其他：</label><input type='text' class='spec-model-input'value=''</div>";*/
    modelHtml = modelHtml + childNode + sureBtn + cancleBtn + "</form></div>";
    $("body").append($(modelContainer).append($(bgHtml)).append($(modalHtml).append($(modelHtml))));
    if(data.length){
        calculateBytesFunc.arr=data;
        $(".readOnlySpecModelHidden").val(calculateBytesFunc.arr.join("|"));
        if(calculateBytesFunc.filterArr.length==0){
            calculateBytesFunc.arr.filter(function(item){
                if(item.trim().length){
                    calculateBytesFunc.filterArr.push(item);
                }
            });
        }
        $(".readOnlySpecModel").val(calculateBytesFunc.filterArr.join("|")).attr("title",calculateBytesFunc.filterArr.join("|"));
        $(".spec-model-input").each(function(i,n){
            if(i==$(".spec-model-input").length-1){
                return;
            }
            var tempVal;
            if($(this).attr("id")=="brandInputDp"||$(this).attr("id")=="disCountInputDp"){
                tempVal=$(this).val().match(/^\d/)[0];
            }else{
                tempVal=$(this).val();
            }
            calculateBytesFunc.bytesLengthArr[i]=calculateBytesFunc._totalBytes(tempVal);
            if($(this).parent().hasClass("required")&& $.trim($(this).val()).length){
                requiredCount++;
            }
        });
        console.log(requiredCount);
        if(calculateBytesFunc.canCalcate){
            calculateBytesFunc.bytesCount=0;
            calculateBytesFunc._sumBytesLengthArr();
            calculateBytesFunc.canCalcate=false;
        }
        $(".lengthTips").find("span").text(calculateBytesFunc.bytesCount);
    }
    var modelInputs = $(".modelContainer input:text");
    var requiredInputLen=modelInputs.parent(".required").length;//总共有几项必填项
    $(".modelContainer").show(0.1, function () {
        $("#modalShow").find(".field").eq(0).find("input").focus();
        //品牌类型下拉数据
        $("#brandInputDp").autocomplete({
                                            source: autocompleteArr[0],
                                            minLength : 0,
                                            select: function( event, ui ) {
                                                if(requiredCount<requiredInputLen){
                                                    requiredCount++;
                                                }
                                                var itemVal = ui.item.value;
                                                if(itemVal){
                                                    itemVal = itemVal.match(/^\d/)[0];
                                                }
                                                calculateBytesFunc._init($(event.target), itemVal);
                                            }
                                        });
        $("#brandInputDp").click(function () {
            $(this).autocomplete("search", "");
        });
        $("#brandInputDp").focus(function () {
            $(this).autocomplete("search", "");
        });
        //出口享惠情况下拉数据
        $("#disCountInputDp").autocomplete({
                                               source: autocompleteArr[1],
                                               minLength : 0,
                                               select: function( event, ui ) {
                                                   if(requiredCount<requiredInputLen){
                                                       requiredCount++;
                                                   }
                                                   var itemVal = ui.item.value;
                                                   if(itemVal){
                                                       itemVal = itemVal.match(/^\d/)[0];
                                                   }
                                                   calculateBytesFunc._init($(event.target), itemVal);
                                               }
                                           });
        $("#disCountInputDp").click(function () {
            $(this).autocomplete("search", "");
        });
        $("#disCountInputDp").focus(function () {
            $(this).autocomplete("search", "");
        });
    });
    /*modelInputs.on("mouseup", function () {
     modelInputs.off("keyup");
     $(this).focus();
     });*/
    //--------弹出商品要素是的特殊处理
    $(".modelContainer").addClass("first-show-no-jump");
    for (var i = 0; i < modelInputs.length; i++) {
        (function (i) {
            var $input = $(modelInputs[i]);
            if (i == modelInputs.length - 1) {//最后一个input,模拟确定动作，光标移动至商品名称
                $input.bind('keyup', function (event) {
                    if (event.keyCode == 13) {
                        $(".modelContainer button[_id='modelSureBtn']").click();
                    }
                });
            } else {
                $input.bind('keyup', function (event) {
                    if(event.keyCode==32&&!$(this).hasClass("ui-autocomplete-input")){
                        calculateBytesFunc._init($(this),$(this).val());
                    }
                    if (event.keyCode == 13) {
                        if ($(this).val().length == 1 && /[是|否|有|无|非]/.test($(this).val())) {
                            $(this).next().remove();
                            $(this).addClass("loadLabelInputError");
                            $(this).after("<div class='loadLabel-error-tips'>录入信息不清晰</div>");
                            return;
                        } else {
                            if ($(this).hasClass("loadLabelInputError")) {
                                $(this).removeClass("loadLabelInputError");
                                $(this).next().remove();
                            }
                            if ($(".modelContainer").hasClass("first-show-no-jump")) {
                                $(".modelContainer").removeClass("first-show-no-jump");
                            } else {
                                $(event.target).declarationJump({action: 'next'});
                            }
                        }
                    }
                });
                $input.on("blur", function (event) {
                    if(!$(this).hasClass("ui-autocomplete-input")){
                        calculateBytesFunc._init($(this),$(this).val(),event);
                    }

                    if ($(this).val().length == 1 && /[是|否|有|无|非]/.test($(this).val())) {
                        $(this).next().remove();
                        $(this).addClass("loadLabelInputError");
                        $(this).after("<div class='loadLabel-error-tips'>录入信息不清晰</div>");
                        $(this).focus();
                        return;
                    } else {
                        if ($(this).hasClass("loadLabelInputError")) {
                            $(this).removeClass("loadLabelInputError");
                            $(this).next().remove();
                            $(this).declarationJump({action: 'next'});
                        }
                        //当满足必填项都填了，去掉必填项的提醒内容
                        if ($(this).parent().hasClass("required")&&!$(this).hasClass("ui-autocomplete-input")) {
                            if ($(this).val()) {
                                requiredCount++;
                            }else{
                                if(requiredCount>0){
                                    requiredCount--;
                                }
                            }
                        }
                        if(requiredCount==requiredInputLen){
                            $(".needRequired").hide();
                        }
                    }
                })
            }
        })(i);

    }
}

function sureFunc(qita, label) {
    var specModelVal = '';
    var count = 0;
    var inputs = $(".spec-model-input");
    var inputsLen = inputs.parent(".required").length;
    var qita_pass = false;
    var compareObj = getDeclarationVal();
    var indexNum = $("#index_num").val();
    var originalVal;
    $.each(inputs, function (i, n) {
        if(i==inputs.length-1){
            return;
        }

        if ($(n).parent().hasClass("required")) {
            if ($(n).val()) {
                /*
                 * 品牌类型和出口享惠情况处理
                 */
                if(i === 0 || i === 1){
                    specModelVal = specModelVal + $(n).val().match(/^\d/) + "|";
                }else{
                    specModelVal = specModelVal + $(n).val() + "|";
                }
                count++;
            } else {
                return false;
            }
        } else {
            if(i !== inputsLen - 1){
                specModelVal = specModelVal + $(n).val() + "|";
            }
            if (qita && (i === inputsLen - 1)) {
                qita_pass = true;
                if ($(n).val()) {
                    specModelVal = specModelVal + $(n).val() + "|";
                }
            } else if (i === inputsLen - 1) {
                specModelVal = specModelVal + $(n).val();
            }
        }
        /*if ($(n).val()) {
         specModelVal = specModelVal + $(n).val() + "|";
         count++;
         console.log(i);
         } else {
         if (qita && (i == inputs.length - 1)) {
         qita_pass = true;
         }
         }*/
    });
    if (specModelVal.length >= 2) {
        specModelVal = specModelVal.substring(0, (specModelVal.length - 1));
    }
    if (inputsLen == count&&(!$(".lengthTips").find("span").hasClass("warnTips")) || qita_pass&&(!$(".lengthTips").find("span").hasClass("warnTips"))) {
        $("#goods_mode").val(specModelVal);
        var useType = $("input[name=actionChain]").val();
        if (useType == "M3" || useType == "C3") {
            if (compareObj.commodities.length >= indexNum) {
                originalVal = compareObj.commodities[indexNum - 1].goods_mode;
                if (specModelVal != originalVal) {
                    $("#goods_mode").addClass("compareTip");
                }
            }

        }
        $(".modelContainer").remove();
        $("input[id='name']").focus();
    }else if(inputsLen != count){
        $(".needRequired").show();
    }
    /*if ($("#commodities").find(".error").length) {
     $('.ui.goodsForm').form('is valid');
     }*/
    if ($("#commodities").find(".error").length) {
        var validteField = ["#code_t", "#goods_mode", "#legalUnitCode"];
        relateValidate("commodities", validteField);
    }
    /*$("input[id='name']").focus();*/
}
function cancleFunc() {
    $(".spec-model-input").val("");
    $(".modelContainer").remove();
    return false;
}

/**
 * 根据字段名及是否禁用的配置设置字段的禁用情况，
 * @param namesDisabledConfig 配置如下:{name1:true,name2:false} name1为字段的name名，true/false为是否禁用，true为禁用，false为启用
 * @param clearValue 是否清理数据
 */
function setNameFieldsDisabled(namesDisabledConfig, clearValue) {
    $.each(namesDisabledConfig, function (i, n) {
        var $field = $("input[name='" + i + "']").parent();
        if ($field.hasClass("error")) {
            $field.removeClass("error");
        }
        var sameAsLastTime = false;
        var currentDisabled = $field.hasClass("disabled");
        if (currentDisabled == n) {
            sameAsLastTime = true;
        }
        if (n) {
            $field.addDisabledClass();
            $field.find("input:text").setTabindex("-1");
        } else {
            $field.removeDisabledClass();
            $field.find("input:text").setTabindex("0");
        }
        if (!sameAsLastTime && clearValue) {
            $field.find("input").val("");
            $field.find("div.text").not("div.default").text("");
        }
    });
}

/**
 * 设置界面必填效果
 * @param configs 示例：{input名:{required:true|false, rule:{验证规则}, members(可选):{input名:true|false},
 *     form_selector:formId， refRule:refRule}
 * @param isMember 是否是组成员 true|false
 * freight1: {
                                        required: true,
                                        members: {
                                            freight1_code: true,
                                            freight2: true,
                                            freight3_code: $("input[name='freight1_code']").valueNotEqual('1'),
                                            freight3: $("input[name='freight1_code']").valueNotEqual('1')
                                        },
                                        ref_form_id: ".ui.allform",
                                        ref_rule: "declarationFormRule"
                                    }
 */

function setInputsRequired(configs, isMember) {
    $.each(configs, function (i, n) {
        var requiredRule = {
            identifier: i.replace("#", ""),
            rules: [
                {
                    type: 'empty',
                    prompt: n.errorText
                }
            ]
        };
        var editValidRules = function (formSelector, refRule, inputName, needValid, newRule) {
            inputName = inputName.replace("#", "");
            var $form = $(formSelector);
            if (needValid) {
                validationRules[refRule].fields[inputName] = newRule;
            } else {
                if (validationRules[refRule].fields[inputName]) {
                    delete validationRules[refRule].fields[inputName];
                }
            }
            $form.form(validationRules[refRule]);
        };
        var __input;
        if (i.indexOf("#") != -1) {
            __input = $(i);
        } else {
            __input = $("input[name='" + i + "']");
        }
        if (!isMember && n.required) {
            __input.parent().prev().addClass("required");
            editValidRules(n.ref_form_id, n.ref_rule, i, true, requiredRule);
        } else {
            __input.parent().prev().removeClass("required");
            editValidRules(n.ref_form_id, n.ref_rule, i, false);
        }
        if (n.members) {
            $.each(n.members, function (j, m) {
                var ruleObj;
                switch (j) {
                    case 'freight2':
                        ruleObj = [
                            {
                                type: 'empty',
                                prompt: '运费值为必填项'
                            },
                            {
                                type: 'regExp[/^0(\.[0-9]{1,4})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,4})?$/]',
                                prompt: '运费值格式错误，不能为负数且保留1-4位小数'
                            },
                            {
                                type: 'maxValue[999999999]',
                                prompt: '运费值允许最大值999999999'
                            }

                        ];
                        break;
                    case 'premium2':
                        ruleObj = [
                            {
                                type: 'empty',
                                prompt: '保费值为必填项'
                            },
                            {
                                type: 'regExp[/^0(\.[0-9]{1,4})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,4})?$/]',
                                prompt: '保费值格式错误，不能为负数且保留1-4位小数'
                            },
                            {
                                type: 'maxValue[999999999]',
                                prompt: '保费值允许最大值999999999'
                            }
                        ];
                        break;
                    case 'otherfee2':
                        ruleObj = [
                            {
                                type: 'empty',
                                prompt: '杂费值为必填项'
                            },
                            {
                                type: 'regExp[/^0(\.[0-9]{1,7})?$|^[1-9][0-9]{0,8}(\.[0-9]{1,7})?$/]',
                                prompt: '杂费值格式错误，保留1-7位小数'
                            },
                            {
                                type: 'maxValue[999999999]',
                                prompt: '杂费值允许最大值999999999'
                            }
                        ]
                        break;
                    default:
                        ruleObj = [{
                                       type: 'empty'
                                   }]

                }
                var memberRequiredRule = {
                    identifier: j,
                    /*rules: [
                     {
                     type: 'empty'
                     }
                     ]*/
                    rules: ruleObj
                };
                memberRequiredRule.identifier = j;
                editValidRules(n.ref_form_id, n.ref_rule, j, m, memberRequiredRule);
            })
        }
    });

}
/**
 * 在只读页面对下拉框数据进行替换，将存贮值转换成显示值
 */
function showDropdownDataWhenReadPageInitialized() {
    //找到需要进行替换操作的下拉框
    var needTranslateDiv = $("div[dropdown_ref]");
    for (var i = 0; i < needTranslateDiv.length; i++) {
        var $div = $(needTranslateDiv[i]);
        var ref = $div.attr("dropdown_ref");
        var ref_value = $div.text();
        second:
            for (var j = 0; j < dropdownConfig.length; j++) {
                var config = dropdownConfig[j];
                //这里不对ajax取值的下拉框进行替换操作
                if (config.key == ref && config.data != null) {
                    var dataArr = config.data;
                    for (var k = 0; k < dataArr.length; k++) {
                        var data = dataArr[k];
                        if (data.code == ref_value) {
                            ref_value = data.name;
                            break second;
                        }
                    }
                }
            }
        $div.text(ref_value);
    }
    //柜表中的柜型的替换
    var $containerTable = $("table[name='containerTable']");
    var $containerTbody = $containerTable.find("tbody");
    var $containerTbodyTrs = $containerTbody.find("tr");
    var containerData = DROPDOWN_DATA.containerType;
    for (i = 0; i < $containerTbodyTrs.length; i++) {
        var $tr = $($containerTbodyTrs[i]);
        var $td = $tr.find("td:eq(1)");
        var text = $td.text();
        for (j = 0; j < containerData.length; j++) {
            data = containerData[j];
            if (data.code == text) {
                text = data.name;
                break;
            }
        }
        $td.text(text);
    }
}
/**
 * 追加jquery对象方法， 设置对象的tabindex至
 * @param tabindex string类型
 */
$.fn.setTabindex = function (tabindex) {
    $(this).attr("tabindex", tabindex);
};
/**
 * 添加disabled样式
 */
$.fn.addDisabledClass = function () {
    var $element = $(this);
    var disabledClassStr = "disabled";
    var isDiv = "DIV" === this.tagName;
    $element.addClass(disabledClassStr);
    if (isDiv) {
        $element.find("input:text").setTabindex("-1");
    }
};
/**
 * 删除disabled样式
 */
$.fn.removeDisabledClass = function () {
    var $element = $(this);
    var disabledClassStr = "disabled";
    var isDiv = "DIV" === this.tagName;
    $element.removeClass(disabledClassStr);
    if (isDiv) {
        $element.find("input:text").setTabindex("0");
    }
};
/**
 * 禁止按tab时进入disabled修饰Div中的input
 */
var invalidInputTabActionOnDisabledDiv = function () {
    $.each($("input:text"), function (i, n) {
        var $dropdownInput = $(n);
        if ($dropdownInput.parent("div").hasClass("disabled")) {
            $dropdownInput.setTabindex("-1");
        }
    });
};

/**
 * 判断input的值是否等于指定值
 * @param value 指定值
 */
$.fn.valueEqual = function (value) {
    var inputValue = $(this).val();
    if (inputValue == undefined || inputValue == "" || inputValue.length === 0) {
        return false;
    }
    return inputValue == value;
}

/**
 * 判断input的值是否不等于指定值,input有值的情况下才会进行比较，false不代表值相等
 * @param value 指定值
 */
$.fn.valueNotEqual = function (value) {
    var inputValue = $(this).val();
    if (inputValue == undefined || inputValue == "" || inputValue.length === 0) {
        return false;
    }
    return inputValue != value;
}

/**
 * 通关一体化校验逻辑
 * 通关一体化检测出口口岸下是不是有线下供应商，没有则不能提交
 * @author han
 * @date 2017-08-25 18:00
 **/
function checkTgyth() {
    var export_port_codeValue = $("input[name='export_port_code']").val();
    var declaration_port_codeValue = $("input[name='declaration_port_code']").val();
    var isTongguanYthVal = jQuery.trim($("input[name='isTongguanYth']").val());
    if (isTongguanYthVal == "1") {
        if (declaration_port_codeValue == export_port_codeValue) {
            layer.alert('通关一体化出口口岸或者进口口岸和申报口岸不能一致');
            return false;
        }
    }
    return true;
}

